package com.any.hook.core.webapi.api;

import com.any.hook.common.exception.HookException;
import com.any.hook.core.webapi.config.WebApiErrorCode;
import com.any.hook.core.webapi.entity.JobInfo;
import com.any.hook.core.webapi.entity.Result;
import com.any.hook.core.webapi.service.EtlJobService;
import com.any.hook.core.webapi.util.ExceptionTracker;
import com.any.hook.core.webapi.util.IDUtils;
import com.any.hook.core.webapi.util.JobStat;
import com.any.hook.core.webapi.util.JobTask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.Callable;

@Controller
public class EtlJobController {
    private static final Logger LOG = LoggerFactory
            .getLogger(EtlJobController.class);

    @Autowired
    private EtlJobService etlJobService;
    @GetMapping("/job/start/{jobid}")
    @ResponseBody
    public Result jobStart(@PathVariable String jobid){
        try{
            if(StringUtils.isBlank(jobid)){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                        String.format("任务id: %s  . 参数校验失败，请核对任务id是否正确 .",jobid));
            }
            Long myJobId=Long.valueOf(jobid);
            String context=etlJobService.getContextByid(myJobId);
            if(StringUtils.isBlank(context)){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                        String.format("给定任务id: %s  . 不能查询到任务内容信息 .",jobid));
            }
            if(etlJobService.changeJobStat(myJobId, JobStat.JOB_START)!=1){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_LOGIC_ERROR,
                        String.format("给定任务id: %s  . 请查看任务，只有不在运行状态的任务才能启动 .",jobid));
            }
            LOG.info(String.format("开始后台执行任务：%s",myJobId));
            new Thread(new JobTask(context,myJobId,etlJobService)).start();
        }catch (Exception e){
            String message;
            if(e instanceof  HookException){
                message=ExceptionTracker.trace(e);
            }else {
                message=ExceptionTracker.trace(HookException.asHookException(WebApiErrorCode.API_RUNTIME_ERROR,e.getCause()));
            }
            return Result.ERRORRESULT(message);
        }
        return Result.SUSSRESULT(1,String.format("开始后台执行任务：%s",jobid));
    }

    @GetMapping("/job/getall/{page}/{size}")
    @ResponseBody
    public Result getAllJobInfo(@PathVariable int page, @PathVariable int size) {
        if( page < 1 || size < 1){
            return Result.ERRORRESULT("指定的参数错误，请核对参数！");
        }
        return Result.SUSSRESULT(etlJobService.getAllJobInfo(page,size));
    }

    @PostMapping("/job/update")
    @ResponseBody
    public Result updateJobInfo(@RequestBody JobInfo jobInfo) {
        JobInfo t=jobInfo;
        if(StringUtils.isBlank(jobInfo.getContext())||StringUtils.isBlank(jobInfo.getName())||jobInfo.getId()<=0){
            return Result.ERRORRESULT("提交的信息内容丢失，请核对提交信息！");
        }
        int count = etlJobService.updateByObject(jobInfo);
        if (count == 1) {
            return Result.SUSSRESULT(1, "数据库信息更新成功！");
        } else {
            return Result.ERRORRESULT("数据库信息更新失败！");
        }
    }
    @PostMapping("/job/save")
    @ResponseBody
    public Result saveJobInfo(@RequestBody JobInfo jobInfo) {
        jobInfo.setId(IDUtils.generateId());
        if(StringUtils.isBlank(jobInfo.getContext())||StringUtils.isBlank(jobInfo.getName())||jobInfo.getId()<=0){
            return Result.ERRORRESULT("提交的信息内容丢失，请核对提交信息！");
        }
        jobInfo.setRunTime(0);
        jobInfo.setStat(0);
        jobInfo.setScheduler("* * * * *");
        int count = etlJobService.saveJobInfo(jobInfo);
        if (count == 1) {
            return Result.SUSSRESULT(1, "数据库信息保存成功！");
        } else {
            return Result.ERRORRESULT("数据库信息保存失败！");
        }
    }
    @GetMapping("/job/resetstat/{jobid}")
    @ResponseBody
    public Result resetJobInfo(@PathVariable String jobid) {
        try{
            if(StringUtils.isBlank(jobid)){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                        String.format("任务id: %s  . 参数校验失败，请核对任务id是否正确 .",jobid));
            }
            Long myJobId=Long.valueOf(jobid);
            int result=etlJobService.changeJobStat(myJobId,JobStat.JOB_STOP);
            if(result!=1){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                        String.format("给定任务id: %s  . 不能查询到任务内容信息 .",jobid));
            }
        }catch (Exception e){
            String message;
            if(e instanceof  HookException){
                message=ExceptionTracker.trace(e);
            }else {
                message=ExceptionTracker.trace(HookException.asHookException(WebApiErrorCode.API_RUNTIME_ERROR,e.getCause()));
            }
            return Result.ERRORRESULT(message);
        }
        return Result.SUSSRESULT(1,String.format("强制重置任务：%s 的状态为初始状态 .",jobid));
    }
    @GetMapping("/job/count")
    @ResponseBody
    public Result getJobInfoCount(){
        return Result.SUSSRESULT(new Integer(etlJobService.selectCount()));
    }
    @GetMapping("/job/deleteby/{jobid}")
    @ResponseBody
    public Result deleteByName(@PathVariable String jobid) {
        try{
            if(StringUtils.isBlank(jobid)){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                        String.format("任务id: %s  . 参数校验失败，请核对任务id是否正确 .",jobid));
            }
            Long myJobId=Long.valueOf(jobid);
            int result=etlJobService.deleteById(myJobId);
            if(result!=1){
                throw HookException.asHookException(WebApiErrorCode.API_JOB_PARAM_CHECKERROR,
                        String.format("给定任务id: %s  . 不能查询到任务内容信息 .",jobid));
            }
        }catch (Exception e){
            String message;
            if(e instanceof  HookException){
                message=ExceptionTracker.trace(e);
            }else {
                message=ExceptionTracker.trace(HookException.asHookException(WebApiErrorCode.API_RUNTIME_ERROR,e.getCause()));
            }
            return Result.ERRORRESULT(message);
        }
        return Result.SUSSRESULT(1,String.format("任务：%s 已经删除 .",jobid));

    }
}
